package com.system.manager.modules.projectLibrary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.manager.common.entity.Result;
import com.system.manager.common.exception.SysException;
import com.system.manager.modules.authorized.entity.Subject;
import com.system.manager.modules.authorized.mapper.UserMapper;
import com.system.manager.modules.projectLibrary.entity.Department;
import com.system.manager.modules.projectLibrary.entity.Project;
import com.system.manager.modules.projectLibrary.mapper.DepartmentMapper;
import com.system.manager.modules.projectLibrary.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jisf
 * @since 2021-11-03
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Department> selectAllDepartment(Subject subject) {
        //获取访问角色的公司
        Integer firm = userMapper.selectById(subject.getId()).getOrganizationId();
        //查询该公司下的所有部门
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","name");
        queryWrapper.eq("firm",firm);
        List<Department> departments = departmentMapper.selectList(queryWrapper);
        return departments;

    }

    @Override
    public Result selectDepartmentByType(Integer page, Integer size, Subject subject) {
        IPage<Department> departmentIPage = new Page<>(page,size);
        //获取访问角色的公司
        Integer firm = userMapper.selectById(subject.getId()).getOrganizationId();
        //查询该公司下的所有部门
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("firm",firm);
        page(departmentIPage, queryWrapper);

        List<Department> records = departmentIPage.getRecords();
        int sizeI = (int)departmentIPage.getSize();
        return Result.ok(records,sizeI);
    }

    @Override
    public void insertDepartment(Subject subject, Department department) {
        //获取访问角色的公司
        Integer firm = userMapper.selectById(subject.getId()).getOrganizationId();
        department.setFirm(firm);
        try {
            departmentMapper.insert(department);
        }catch (Exception e){
            throw new SysException();
        }
    }

    @Override
    public void deleteDepartment(Integer id) {
        try {
            departmentMapper.deleteById(id);
        }catch (Exception e){
            throw new SysException();
        }
    }
}
